<template>
  <a-modal v-model:visible="visible" :title="title" :width="600" :mask-closable="false" @cancel="handleCancel">
    <a-form
      ref="FormRef"
      :model="formFields"
      :rules="formRules"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 16 }"
      autocomplete="off"
    >
      <a-form-item label="代理商ID" name="proxyId">
        <a-input
          :maxlength="9"
          v-model:value.trim.number="formFields.proxyId"
          placeholder="请输入代理商ID"
          allow-clear
        />
      </a-form-item>

      <a-form-item label="客户名称" name="name">
        <a-input :maxlength="30" v-model:value.trim="formFields.name" placeholder="请输入客户名称" allow-clear />
      </a-form-item>

      <a-form-item label="代理商UID" name="bxProxyId">
        <a-input
          :maxlength="9"
          v-model:value.trim.number="formFields.bxProxyId"
          placeholder="请输入代理商UID"
          allow-clear
        />
      </a-form-item>
    </a-form>

    <template #footer>
      <a-button key="submit" type="primary" :loading="submitting" @click="handleSubmit"> 提交 </a-button>
      <a-button key="back" @click="handleCancel"> 取消 </a-button>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { useVModel } from '@vueuse/core'
import type { FormInstance } from 'ant-design-vue'
import type { BaixingAccountParams } from '@/services/account-management/updateBaixingAccount'
import { checkNumber } from '@/utils'
import { Mode } from '@/core/interfaces/common'

interface Props {
  show: boolean
  mode: Mode
  data: BaixingAccountParams
  submitting: boolean
}

interface Emits {
  (e: 'on-submit'): void
}

const props = withDefaults(defineProps<Props>(), {
  mode: Mode.create,
  show: false
})
const emit = defineEmits<Emits>()

const visible = useVModel(props, 'show')
const formFields = useVModel(props, 'data')
const FormRef = ref<FormInstance>()
const title = computed(() => {
  return props.mode === Mode.create ? '创建百姓网账号' : '编辑百姓网账号'
})

const formRules = reactive({
  proxyId: [
    {
      required: true,
      trigger: 'blur',
      validator: checkNumber(['请输入代理商ID', '代理商ID必须为数字'])
    }
  ],
  bxProxyId: [
    {
      required: true,
      trigger: 'blur',
      validator: checkNumber(['请输入客户百姓网ID', '客户百姓网ID必须为数字'])
    }
  ],
  name: [
    {
      required: true,
      message: '请输入客户名称',
      trigger: 'blur'
    }
  ]
})

function handleSubmit() {
  FormRef.value?.validate().then(() => {
    emit('on-submit')
  })
}

function handleCancel() {
  FormRef.value?.resetFields()
  visible.value = false
}
</script>

<script lang="ts">
export default { name: 'AccountUpdater' }
</script>
